<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <canvas id="myCanvas" width="500" height="500"></canvas>
</body>
<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    let currentScale = 1;
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    let scale = 1;
    let originX = 0;
    let originY = 0;

    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 应用当前变换
        ctx.save();
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.translate(originX, originY);
        ctx.scale(scale, scale);

        const p = new Path2D;
        p.rect(-50, -50, 100, 100);
        ctx.stroke(p);

        ctx.restore();
    }

    canvas.addEventListener('wheel', (e) => {
        e.preventDefault();

        // 获取鼠标位置（Canvas坐标）
        const mouseX = e.clientX - canvas.getBoundingClientRect().left;
        const mouseY = e.clientY - canvas.getBoundingClientRect().top;

        // 计算缩放前后的坐标关系
        const newScale = e.deltaY < 0 ? scale * 1.1 : scale / 1.1;
        const ratio = 1 - newScale / scale;

        // 更新原点和缩放比例
        originX += (mouseX - originX) * ratio;
        originY += (mouseY - originY) * ratio;
        scale = newScale;

        draw();
    });
</script>

</html>